package com.wocai.jrt.orgadmin.enterprise.action;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.wocai.jrt.orgadmin.enterprise.model.Enterprise;
import com.wocai.jrt.orgadmin.enterprise.model.EnterpriseAttachment;
import com.wocai.jrt.orgadmin.enterprise.model.EnterpriseShareholder;
import com.wocai.jrt.orgadmin.enterprise.model.EnterpriseWithBLOBs;
import com.wocai.jrt.orgadmin.enterprise.model.FinancialAssetsLiabilities;
import com.wocai.jrt.orgadmin.enterprise.model.FinancialCashFlow;
import com.wocai.jrt.orgadmin.enterprise.model.FinancialProfit;
import com.wocai.jrt.orgadmin.enterprise.model.FinancialReport;
import com.wocai.jrt.orgadmin.enterprise.service.spi.EnterpriseAttachmentService;
import com.wocai.jrt.orgadmin.enterprise.service.spi.EnterpriseService;
import com.wocai.jrt.orgadmin.enterprise.service.spi.EnterpriseShareholderService;
import com.wocai.jrt.orgadmin.enterprise.service.spi.FinancialAssetsLiabilitiesService;
import com.wocai.jrt.orgadmin.enterprise.service.spi.FinancialCashFlowService;
import com.wocai.jrt.orgadmin.enterprise.service.spi.FinancialProfitService;
import com.wocai.jrt.orgadmin.enterprise.service.spi.FinancialReportService;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 企业控制器
 * @author yinlei
 * @date 2016-5-6 14:22:15
 */
@Controller
@RequestMapping("/enterprise")
public class EnterpriseAction extends GenericAction<Enterprise> {
	private static final Logger LOGGER = LoggerFactory.getLogger(EnterpriseAction.class);
	
	@Inject
	private EnterpriseService enterpriseServiceImpl;
	@Inject
	private EnterpriseShareholderService enterpriseShareholderServiceImpl;
	@Inject
	private EnterpriseAttachmentService enterpriseAttachmentServiceImpl;
	@Inject 
	private FinancialReportService financialReportServiceImpl;
	@Inject 
	private FinancialProfitService financialProfitServiceImpl;
	@Inject 
	private FinancialCashFlowService financialCashFlowServiceImpl;
	@Inject 
	private FinancialAssetsLiabilitiesService financialAssetsLiabiltiesServiceImpl;
	/**
     * 获得企业List，初始化列表页。
     * @param model 参数
     * @return 企业List
     */
    @RequestMapping("/initial")
    public String initial(Enterprise model, Map<String, Object> maps) {
    	try {
    		List<Enterprise> list = enterpriseServiceImpl.pagedList(model);
            maps.put("list", list);
		} catch (Exception e) {
			LOGGER.error("get record list error, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
        return "enterprise/initial";
    }
	
	/**
	 * 获得企业List，Json格式。
	 * @param model 参数
	 * @return 企业List
	 */
	@ResponseBody
	@RequestMapping("/list")
	public List<Enterprise> list(Enterprise model) {
		List<Enterprise> list = null;
		try {
			list = enterpriseServiceImpl.pagedList(model);
		} catch (Exception e) {
			LOGGER.error("get record list error, errorMsg=[{}].", e.getMessage());
		}
		return list;
	}
	
	/**
     * 根据Id获得企业实体，Json格式。
     * @param id 参数id
     * @return 企业实体
     */
    @ResponseBody
    @RequestMapping("/get")
    public Enterprise get(String id) {
    	Enterprise model = null;
    	try {
    		model = enterpriseServiceImpl.get(id);
		} catch (Exception e) {
			LOGGER.error("get record error, errorMsg=[{}].", e.getMessage());
		}
        return model;
    }
	
	/**
     * 跳转到新增页面
     * @return 新增页面逻辑视图
     */
    @RequestMapping("/add")
    public String add() {
        return "enterprise/add";
    }
    
    /**
     * 新增企业基本信息
     * @param model 要新增的数据
     * @return 新增页面逻辑视图
     */
    @ResponseBody
    @RequestMapping("/doAdd")
    public JsonBean doAdd(@RequestBody EnterpriseWithBLOBs model) {
    	JsonBean bean = new JsonBean();
    	try {
    		LOGGER.info("Enterprise doAdd params is [{}]",JSON.toJSONString(model));
    		
    		String id = ObjectId.get().toString();
    		model.setId(id);
    		model.setOrgId(UserUtils.getOrgId());
    		if(StringUtils.isNotBlank(model.getIntroduction())){
    			model.setIntroduction(java.net.URLDecoder.decode(model.getIntroduction(),"UTF-8"));	
    		}
    		int result = enterpriseServiceImpl.save(model);
            if (result == 1) {
                bean.setMessage(SUCCESS);
                bean.setCode(1);
                bean.setData(id);
                LOGGER.info("save record success.");
            } else {
                bean.setMessage(ERROR);
                LOGGER.error("save record error.");
            }
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("save record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
        return bean;
    }
    
    /**
     * 新增企业股东
     */
    @ResponseBody
    @RequestMapping("/addShareholder")
    public JsonBean addShareholder(@RequestBody EnterpriseShareholder model) {
    	JsonBean bean = new JsonBean();
    	try {
    		LOGGER.info("Enterprise Shareholder doAdd params is [{}]",JSON.toJSONString(model));
    		String id = ObjectId.get().toString();
    		model.setId(id);
    		model.setOrgId(UserUtils.getOrgId());
    		int result = enterpriseShareholderServiceImpl.save(model);
            if (result == 1) {
                bean.setMessage(SUCCESS);
                bean.setCode(1);
                bean.setData(id);
                LOGGER.info("save  Shareholder record success.");
            } else {
                bean.setMessage(ERROR);
                LOGGER.error("save Shareholder record error.");
            }
		} catch (Exception e) {
			LOGGER.error("save Shareholder record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
        return bean;
    }
    
    /**
     * 删除企业股东
     */
    @ResponseBody
    @RequestMapping("/delShareholder")
    public JsonBean delShareholder(@RequestBody EnterpriseShareholder model) {
    	JsonBean bean = new JsonBean();
    	try {
    		if(StringUtils.isBlank(model.getId())){
    			  bean.setMessage(ERROR);
                  LOGGER.error("delShareholder params(id) is null .");
    		}
    		LOGGER.info("Enterprise delShareholder params is [{}]",JSON.toJSONString(model));
    		int result = enterpriseShareholderServiceImpl.deleteById(model.getId());
            if (result == 1) {
                bean.setMessage(SUCCESS);
                bean.setCode(1);
                LOGGER.info("del  Shareholder record success.");
            } else {
                bean.setMessage(ERROR);
                LOGGER.error("del Shareholder record error.");
            }
		} catch (Exception e) {
			LOGGER.error("save Shareholder record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
        return bean;
    }
    
    /**
     *  新增企业财务报表数据
     */
    @ResponseBody
    @RequestMapping("/addFinancialReport")
    public JsonBean addFinancialReport(@RequestBody FinancialReport model) {
    	JsonBean bean = new JsonBean();
    	try {
    		if(StringUtils.isAnyBlank(model.getEnterpriseId(),model.getReportCompany())){
    			  bean.setMessage(ERROR);
                  LOGGER.error("addFinancialReport params(EnterpriseId,ReportCompany) is null .");
    		}
    		LOGGER.info("Enterprise addFinancialReport params is [{}]",JSON.toJSONString(model));
    		String id = ObjectId.get().toString();
    		model.setId(id);
    		model.setCreateTime(new Date());
    		model.setEmployeeId(UserUtils.getUserId());
    		int result = financialReportServiceImpl.save(model);
    		//新建利润表数据
    		FinancialProfit fp = new FinancialProfit();
    		fp.setFinancialReportId(id);
    		fp.setId(ObjectId.get().toString());
			financialProfitServiceImpl.save(fp);
			//新建现金流量表数据
			FinancialCashFlow fcf = new FinancialCashFlow();
			fcf.setFinancialReportId(id);
			fcf.setId(ObjectId.get().toString());
			financialCashFlowServiceImpl.save(fcf);
			//新建资产负债表数据
			FinancialAssetsLiabilities falb = new FinancialAssetsLiabilities();
			falb.setFinancialReportId(id);
			falb.setId(ObjectId.get().toString());
			financialAssetsLiabiltiesServiceImpl.save(falb);
            if (result == 1) {
                bean.setMessage(SUCCESS);
                bean.setData(id);
                bean.setCode(1);
                LOGGER.info("add FinancialReport  record success.");
            } else {
                bean.setMessage(ERROR);
                bean.setCode(0);
                LOGGER.error("add FinancialReport record error.");
            }
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("add FinancialReport record error, errorMsg=[{}].", e.getMessage());
			bean.setCode(0);
			bean.setMessage(ERROR);
		}
        return bean;
    }
    
    /**
     * 更新企业资产负债数据
     */
    @ResponseBody
    @RequestMapping("/saveAssetLiability")
    public JsonBean saveAssetLiability(@RequestBody FinancialAssetsLiabilities model) {
    	JsonBean bean = new JsonBean();
    	try {
    		LOGGER.info(" enterprise saveAssetLiability the params is [{}]",JSON.toJSONString(model));
    		FinancialAssetsLiabilities falb = new FinancialAssetsLiabilities();
    		falb.setFinancialReportId(model.getFinancialReportId());
    		FinancialAssetsLiabilities falbTemp =financialAssetsLiabiltiesServiceImpl.unique(falb);
    		int result = 0;
    		if(falbTemp == null){
    			model.setId(ObjectId.get().toString());
    			result = financialAssetsLiabiltiesServiceImpl.save(model);
    		}else{
    			model.setId(falbTemp.getId());
    			result = financialAssetsLiabiltiesServiceImpl.updateById(model);
    		}
    		if(result == 1){
    			 bean.setMessage("更新企业资产负债数据成功");
                 bean.setCode(1);
    		}else{
    			 bean.setMessage("更新企业资产负债数据失败");
                 bean.setCode(0);
    		}
		} catch (Exception e) {
			LOGGER.error("query record detail, errorMsg=[{}].", e.getMessage());
		}
        return bean;
    }
    
    /**
     * 更新企业利润表数据
     */
    @ResponseBody
    @RequestMapping("/saveProfit")
    public JsonBean saveProfit(@RequestBody FinancialProfit model) {
    	JsonBean bean = new JsonBean();
    	try {
    		LOGGER.info(" enterprise saveProfit the params is [{}]",JSON.toJSONString(model));
    		FinancialProfit falb = new FinancialProfit();
    		falb.setFinancialReportId(model.getFinancialReportId());
    		FinancialProfit falbTemp =financialProfitServiceImpl.unique(falb);
    		int result = 0;
    		if(falbTemp == null){
    			model.setId(ObjectId.get().toString());
    			result = financialProfitServiceImpl.save(model);
    		}else{
    			model.setId(falbTemp.getId());
    			result = financialProfitServiceImpl.updateById(model);
    		}
    		if(result == 1){
    			 bean.setMessage("更新企业利润表数据成功");
                 bean.setCode(1);
    		}else{
    			 bean.setMessage("更新企业利润表数据失败");
                 bean.setCode(0);
    		}
		} catch (Exception e) {
			LOGGER.error(" enterprise saveProfit detail, errorMsg=[{}].", e.getMessage());
		}
        return bean;
    }
    
    /**
     * 更新企业现金流量表数据
     */
    @ResponseBody
    @RequestMapping("/saveCash")
    public JsonBean saveCash(@RequestBody FinancialCashFlow model) {
    	JsonBean bean = new JsonBean();
    	try {
    		LOGGER.info(" enterprise saveCash the params is [{}]",JSON.toJSONString(model));
    		FinancialCashFlow falb = new FinancialCashFlow();
    		falb.setFinancialReportId(model.getFinancialReportId());
    		FinancialCashFlow falbTemp =financialCashFlowServiceImpl.unique(falb);
    		int result = 0;
    		if(falbTemp == null){
    			model.setId(ObjectId.get().toString());
    			result = financialCashFlowServiceImpl.save(model);
    		}else{
    			model.setId(falbTemp.getId());
    			result = financialCashFlowServiceImpl.updateById(model);
    		}
    		if(result == 1){
    			 bean.setMessage("更新企业现金流量表数据成功");
                 bean.setCode(1);
    		}else{
    			 bean.setMessage("更新企业现金流量表数据失败");
                 bean.setCode(0);
    		}
		} catch (Exception e) {
			LOGGER.error(" enterprise saveCash detail, errorMsg=[{}].", e.getMessage());
		}
        return bean;
    }
    
    /**
     * 更新企业财务指标数据
     */
    @ResponseBody
    @RequestMapping("/saveFinance")
    public JsonBean saveFinance(@RequestBody FinancialAssetsLiabilities model) {
    	JsonBean bean = new JsonBean();
    	try {
    		LOGGER.info(" enterprise saveAssetLiability the params is [{}]",JSON.toJSONString(model));
    		model.setId(ObjectId.get().toString());
    		int result = financialAssetsLiabiltiesServiceImpl.save(model);
    		if(result == 1){
    			 bean.setMessage("更新企业资产负债数据成功");
                 bean.setCode(1);
    		}else{
    			 bean.setMessage("更新企业资产负债数据失败");
                 bean.setCode(0);
    		}
		} catch (Exception e) {
			LOGGER.error("query record detail, errorMsg=[{}].", e.getMessage());
		}
        return bean;
    }
    /**
     * 查看企业详情页。
     * @param model 查询参数，携带ID
     * @return 企业详情页
     */
    @RequestMapping("/detail/{id}")
    public String detail(@PathVariable("id") String id, Map<String, Object> maps) {
    	try {
    		Enterprise model = enterpriseServiceImpl.get(id);
            maps.put("model", model);//将model放入视图中，供页面视图使用
            //获取企业股东信息
            EnterpriseShareholder params = new EnterpriseShareholder();
            params.setEnterpriseId(id);
            List<EnterpriseShareholder> shareList = enterpriseShareholderServiceImpl.pagedList(params);
            maps.put("shareList", shareList);
            EnterpriseAttachment ea = new EnterpriseAttachment();
            ea.setEnterpriseId(id);
            List<EnterpriseAttachment> eaList = enterpriseAttachmentServiceImpl.pagedList(ea);
            maps.put("eaList", eaList);
		} catch (Exception e) {
			LOGGER.error("query record detail, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
        return "enterprise/detail";
    }
    
    /**
     * 跳转到编辑信息页面
     * @param model 查询参数，携带ID
     * @return 编辑页面
     */
    @RequestMapping("/edit")
    public String edit(Enterprise model, Map<String, Object> maps) {
        model = enterpriseServiceImpl.get(model.getId());
        maps.put("model", model);
        return "enterprise/edit";
    }
    
    /**
     * 更新企业信息
     * @param model 要更新的企业信息，含有ID
     * @return 操作结果信息
     */
    @ResponseBody
    @RequestMapping("/update")
    public JsonBean update(@RequestBody EnterpriseWithBLOBs model) {
    	JsonBean bean = new JsonBean();
    	try {
    		if(StringUtils.isBlank(model.getId())){
    			  bean.setMessage("update Enterprise info params error");
                  bean.setCode(0);
                  LOGGER.info("update Enterprise info params error");
                  return bean;
    		}
    		//对富文本内容进行解码
    		if(StringUtils.isNotBlank(model.getCoreMembersIntroduction())){
    			model.setCoreMembersIntroduction(java.net.URLDecoder.decode(model.getCoreMembersIntroduction(),"UTF-8"));	
    		}
    		if(StringUtils.isNotBlank(model.getMainBusiness())){
    			model.setMainBusiness(java.net.URLDecoder.decode(model.getMainBusiness(),"UTF-8"));	
    		}
    		if(StringUtils.isNotBlank(model.getIndustrySituation())){
    			model.setIndustrySituation(java.net.URLDecoder.decode(model.getIndustrySituation(),"UTF-8"));	
    		}
    		if(StringUtils.isNotBlank(model.getCompetitivePosition())){
    			model.setCompetitivePosition(java.net.URLDecoder.decode(model.getCompetitivePosition(),"UTF-8"));	
    		}
    		if(StringUtils.isNotBlank(model.getMainAssetConditions())){
    			model.setMainAssetConditions(java.net.URLDecoder.decode(model.getMainAssetConditions(),"UTF-8"));	
    		}
    		if(StringUtils.isNotBlank(model.getCompetitivePosition())){
    			model.setCompetitivePosition(java.net.URLDecoder.decode(model.getCompetitivePosition(),"UTF-8"));	
    		}
    		if(StringUtils.isNotBlank(model.getBusinessModel())){
    			model.setBusinessModel(java.net.URLDecoder.decode(model.getBusinessModel(),"UTF-8"));	
    		}
    		if(StringUtils.isNotBlank(model.getBusinessOther())){
    			model.setBusinessOther(java.net.URLDecoder.decode(model.getBusinessOther(),"UTF-8"));	
    		}
    		if(StringUtils.isNotBlank(model.getProfitForecast())){
    			model.setProfitForecast(java.net.URLDecoder.decode(model.getProfitForecast(),"UTF-8"));	
    		}
    		if(StringUtils.isNotBlank(model.getFinanciaOther())){
    			model.setFinanciaOther(java.net.URLDecoder.decode(model.getFinanciaOther(),"UTF-8"));	
    		}
    		int result = enterpriseServiceImpl.updateById(model);
            if (result == 1) {
                bean.setMessage(SUCCESS);
                bean.setCode(1);
                LOGGER.info("update enterprise record success.");
            } else {
                bean.setMessage(ERROR);
                LOGGER.error("update enterprise record error.");
            }
		} catch (Exception e) {
			LOGGER.error("update enterprise record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
        return bean;
    }
    
    /**
     * 检查企业名称是否已经被使用
     * @param model
     * @return
     */
    @ResponseBody
	@RequestMapping("/check")
	public boolean check(EnterpriseWithBLOBs model) {
		model.setOrgId(UserUtils.getOrgId());
		if (StringUtils.isNotBlank(model.getName())) {
			model.setName(model.getName());
			List<Enterprise> list = enterpriseServiceImpl.pagedList(model);
			if(list.size() > 0){
				return false;
			}
			return true;
		} else {
			return true;
		}
	}
}
